package com.teamin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.core.util.StringUtils;
import com.teamin.config.ErrorCode;
import com.teamin.config.MessageType;
import com.teamin.config.TaskMessageType;
import com.teamin.entity.*;
import com.teamin.mapper.MessageEntityMapper;
import com.teamin.mapper.MessageMapper;
import com.teamin.mapper.TaskMapper;
import com.teamin.service.CircleService;
import com.teamin.service.MessageService;
import com.teamin.service.UserService;
import com.teamin.service.WebsocketService;
import com.teamin.service.impl.wx.SmallMessageManager;
import com.teamin.service.impl.wx.WXMPTemplate;
import com.teamin.service.impl.wx.WXSendMessage;
import com.teamin.service.impl.wx.WXSmallTemplate;
import com.teamin.utils.Utils;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import com.teamin.web.socket.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class MessageServiceImpl implements MessageService{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private MessageMapper messageMapper;
	@Autowired
	private MessageEntityMapper messageEntityMapper;

	@Autowired
	private CircleService circleService;

	@Autowired
	private TaskMapper taskMapper;

	@Autowired
	private WebsocketServiceImpl websocketService ;

	@Autowired
	private TaskServiceImpl taskService;

	@Autowired
	private UserService userService;

	@Autowired
	WXSmallTemplate wxSmallTemplate ;

	@Autowired
	WXMPTemplate wxmpTemplate ;

	public class ChangeValue {
		Object newValue ;
		Object oldValue ;
		ChangeValue(Object newValue,Object oldValue) {
			this.newValue = newValue ;
			this.oldValue = oldValue ;
		}
	}

	@Override
	public List<MessageEntity> getMessageByUserAndCircle(Long userId,Long circleId) throws GlobalErrorInfoException {
		try {
			return messageMapper.getMessageByUserAndCircle(userId, circleId);
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST	, ErrorCode.FIND_MESSAGE_FAIL));
		}

	}

	@Override
	public MessageEntity selectByPrimaryKey(Long messageId){
		try {
			MessageEntity messageEntity = messageMapper.selectByPrimaryKey(messageId);
			if (messageEntity == null) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_MESSAGE_NULL));
			}
			return messageEntity;
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
		}
		return null ;
	}

	/**
	 * 比较两个任务的不同的属性,
	 * 现只对执行者,状态属性作比较
	 * @param n 新任务的
	 * @param o 老任务
	 * @return
	 */
	public Map<String,Object> getChangePropertis(TaskEntity n, TaskEntity o) {

		Map<String,Object> s = new HashMap<>() ;
		if (!(""+n.getAssigner()).equals(o.getAssigner()) ) {
			s.put(TASK_TYPE_ASSIGNER,new ChangeValue(n.getAssigner(),o.getAssigner())) ;
		}

		if (n.getStateId() != o.getStateId()) {
			s.put(TASK_TYPE_STATE_ID,new ChangeValue(n.getStateId(),o.getStateId())) ;
		}
		return s ;
	}

	/**
	 * 创建通知消息
	 *
	 * @param
	 */
	@Override
	public void updateTaskMessage(TaskEntity oldTask, TaskEntity newTask, Long controlUserId,String userFlag) {
		// 新任务
		// 任务所属圈子
		CircleEntity circleEntities = taskService.getCirclesByTask(oldTask.getTaskId(),controlUserId);
		NotifiEntity controlUser = messageMapper.getMPOpenId(controlUserId, circleEntities.getCircleId());
		try {
			String taskType = "" ;
			if(newTask.getLabels() != null && newTask.getLabels().size() !=0) {
				for(int i = 0 ;( i < newTask.getLabels().size() && i< 3); i ++) {
					taskType +=(i!=0?" ":"")+newTask.getLabels().get(i).getLabelName() ;
				}
			}else {
				taskType="未指定" ;
			}

			if (!(""+newTask.getAssignerId()).equals(""+oldTask.getAssignerId())) {
				// 任务所属圈子
				NotifiEntity newUser = messageMapper.getMPOpenId(newTask.getAssignerId(),circleEntities.getCircleId()) ;
				NotifiEntity oldUser = messageMapper.getMPOpenId(oldTask.getAssignerId(),circleEntities.getCircleId()) ;

				//Long mId = createNewTaskMessage(newTask, circleEntities.getCircleId(), controlUserId);

				List<Long> excludeUser = new ArrayList<>() ;
				if(oldTask != null && oldTask.getAssignerId() != null){
					excludeUser.add(oldTask.getAssignerId()) ;
				}

				//要通知的成员
				List<NotifiEntity> userList = messageMapper.getTaskNotifiAttentionAndAssigner(oldTask.getTaskId(),excludeUser);
				if(oldTask != null && oldTask.getAssignerId() != null){
					userList.add(oldUser) ;
				}

				Map<NotifiEntity, Long> notiUser = addTaskMessage(newTask, userList, circleEntities.getCircleId(), TaskMessageType.TASK_ASSIGNER, controlUserId, (oldTask==null?null:oldTask.getAssignerId()),(oldTask==null?null:oldTask.getAssignerUserName()),(newTask==null?null:newTask.getAssignerId()),(newTask==null?null:newTask.getAssignerUserName()));

				if(notiUser != null && notiUser.size() >0 ) {

					Iterator<Map.Entry<NotifiEntity, Long>> iter = notiUser.entrySet().iterator();;
					while(iter.hasNext()) {
                        Map.Entry<NotifiEntity, Long> next = iter.next();;
                        NotifiEntity k = next.getKey();;
						Long v = next.getValue() ;
						String notifiString ;
						if(newUser != null && !StringUtils.isNullOrEmpty(newUser.getUserName()) && newUser.getUserId()==controlUserId) {
							notifiString = "有新的任务指派给你" ;
						}else if(newUser == null || StringUtils.isNullOrEmpty(newUser.getUserName())) {
							notifiString = "清空执行者" ;
						}else  {
							notifiString = "修改任务执行者为"+newUser.getUserName();
						}

						websocketService.sendToCircleUserNotifi(newTask.getAssignerId(),controlUserId,circleEntities.getCircleId(), WebsocketService.NotifiPropertise.ASSIGNERED,v,userFlag);
						if(SessionManager.userOnline(String.valueOf(k.getUserId()))) {//在线发送通知
							websocketService.sendToUserNotifi(k.getUserId(),controlUserId,circleEntities.getCircleId(), WebsocketService.NotifiPropertise.TASK_ASSIGNERED,selectByPrimaryKey(v),userFlag) ;
						}else if( k.getUserId() != controlUserId && k != null && !StringUtils.isNullOrEmpty(k.getMpOpenId())) {//公众号通知
							JSONObject json ;
							//发送任务执行人的通知
							if(newUser != null) {
								if (newUser.getUserId() == k.getUserId()) {
									json = wxmpTemplate.taskAssignerChangeTemplate("有新的任务指派给你",newTask.getTaskName(),taskType,newUser.getUserName(),
											controlUser.getUserName(), k.getMpOpenId(), circleEntities.getCircleId(), oldTask.getTaskId());
								} else {//发给关注者的通知
									json = wxmpTemplate.taskAssignerChangeTemplate("",newTask.getTaskName(),"",newUser.getUserName(),
											controlUser.getUserName(), k.getMpOpenId(), circleEntities.getCircleId(), oldTask.getTaskId());
								}
							}else {
								json = wxmpTemplate.taskAssignerChangeTemplate("",newTask.getTaskName(),taskType,"未指定",
										controlUser.getUserName(),k.getMpOpenId(),circleEntities.getCircleId(),oldTask.getTaskId());;
							}
							WXSendMessage.getInstance().postMessage(json);
						}else if( k.getUserId() != controlUserId && k != null && !StringUtils.isNullOrEmpty(k.getSmallOpenId())) {//小程序服务通知
							String fromId = userService.getFromId(k.getUserId());
							if (!StringUtils.isNullOrEmpty(fromId)) { //服务号消息的发送
								JSONObject json = wxSmallTemplate.createNewTaskTemplate(circleEntities.getCircleName(), oldTask.getTaskName(),notifiString
										, k.getSmallOpenId(), circleEntities.getCircleId(), oldTask.getTaskId(), fromId);
								SmallMessageManager.sendTemplateMessage(json);
								userService.updateSmallFromIdState(k.getUserId(), fromId, UserService.SMALL_FROM_ID_STATE_USED);
							}
						}
					}
				}


//				if(oldTask.getAssignerId() != null && !oldTask.getAssignerId().equals(controlUserId ) && oldUser!= null && !StringUtils.isNullOrEmpty(oldUser.getMpOpenId())) {
//					JSONObject jsonObject = wxmpTemplate.taskAssignerChangeTemplate(newTask.getTaskName(), Utils.getFormatDateTime(System.currentTimeMillis()), controlUser.getUserName() + (newUser==null?"清空执行者":"修改任务执行者为" + newUser.getUserName()), oldUser.getMpOpenId(), "",circleEntities.getCircleId(),oldTask.getTaskId());;
//					WXSendMessage.getInstance().postMessage(jsonObject);
//				} else if(oldTask.getAssignerId() != null && !oldTask.getAssignerId().equals(controlUserId ) && oldUser!= null && !StringUtils.isNullOrEmpty(oldUser.getSmallOpenId())) {
//					String fromId = userService.getFromId(oldUser.getUserId());
//					if(!StringUtils.isNullOrEmpty(fromId)) {
//						JSONObject jsonObject = wxSmallTemplate.taskAssignerChangeTemplate(circleEntities.getCircleName(),newTask.getTaskName(), controlUser.getUserName() + (newUser==null?"清空执行者":"修改任务执行者为" + newUser.getUserName()), oldUser.getSmallOpenId(),circleEntities.getCircleId(),oldTask.getTaskId(),fromId);
//						SmallMessageManager.sendTemplateMessage(jsonObject);
//						userService.updateSmallFromIdState(oldUser.getUserId(),fromId,UserService.SMALL_FROM_ID_STATE_USED) ;
//					}
//				}
			}
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}

//		// 任务完成通知
//		try {
//			Integer stateId = newTask.getStateId();
//			if (stateId != null && stateId == 3 && !stateId.equals(oldTask.getStateId())) {
//				Long taskiId = oldTask.getTaskId();
//				// 要通知的人
//				List<NotifiEntity> userList = messageMapper.getTaskNotifiUser(oldTask.getTaskId());;
//				StringBuffer sb = new StringBuffer() ;
//				// 循环要通知的用户
//				for (NotifiEntity us  : userList) {
//					//不是操作者则发送消息{
//					if(!controlUserId.equals(us.getUserId())) {
//						addTaskMessage(newTask, us.getUserId(), circleEntities.getCircleId(), TaskMessageType.FINISH_TASK,controlUserId,null);
//						if(!StringUtils.isNullOrEmpty(us.getMpOpenId())){
//							String first ;
//							if(us.getUserId() != null && us.getUserId().equals(newTask.getAssignerId())) {
//								first = "你的任务已完成" ;
//							}else if(us.getUserId() != null && us.getUserId().equals(newTask.getCreaterId())) {
//								first = "你创建的任务已完成" ;
//							}else {
//								first = "你关注的任务已完成" ;
//							}
//							JSONObject jsonObject = WXTaskTemplate.taskFinish(first,oldTask.getTaskName(),us.getMpOpenId(),"",circleEntities.getCircleId(),oldTask.getTaskId()) ;
//							WXSendMessage.getInstance().postMessage(jsonObject);
//						}
//					}
//
//				}
//			}
//		} catch (Exception e) {
//			logger.warn(e.getMessage(), e);
//		}
	}


	/**
	 * 删除任务的消息提醒
	 * @param taskEntitye
	 * @param circleEntities
	 * @param controlUserId
	 */
	@Override
	public void deleteTaskMessage(TaskEntity taskEntitye, CircleEntity circleEntities, Long controlUserId,String userFlag) {

		List<NotifiEntity> userList = messageMapper.getTaskNotifiAttentionAndAssigner(taskEntitye.getTaskId(),null);

		Map<NotifiEntity, Long> notiUser = addTaskMessage(taskEntitye, userList, circleEntities.getCircleId(), TaskMessageType.Task_DELETE, controlUserId, null,null,null,null);


		if(notiUser != null && notiUser.size() >0 ) {
			NotifiEntity controlUser = messageMapper.getMPOpenId(controlUserId,circleEntities.getCircleId()) ;
			notiUser.forEach((k,v)->{
					NotifiEntity newUser = messageMapper.getMPOpenId(k.getUserId(),circleEntities.getCircleId()) ;
					if(SessionManager.userOnline(String.valueOf(k.getUserId()))) {//在线发送通知
						websocketService.sendToUserNotifi(k.getUserId(),controlUserId,circleEntities.getCircleId(), WebsocketService.NotifiPropertise.TASK_DELETE,selectByPrimaryKey(v),userFlag) ;
					}else if( k.getUserId() != controlUserId && newUser != null && !StringUtils.isNullOrEmpty(newUser.getMpOpenId())) {//公众号通知
						JSONObject json = wxmpTemplate.deleteTask(taskEntitye.getTaskName(),controlUser.getUserName(),
								Utils.getFormatDateTime(System.currentTimeMillis()), newUser.getMpOpenId() , "点击查看详情",circleEntities.getCircleId(),taskEntitye.getTaskId());
						WXSendMessage.getInstance().postMessage(json);
					}else if(k.getUserId() != controlUserId && k != null && !StringUtils.isNullOrEmpty(k.getSmallOpenId())) {//小程序服务通知
						String fromId = userService.getFromId(k.getUserId());
						if (!StringUtils.isNullOrEmpty(fromId)) { //服务号消息的发送
							JSONObject json = wxSmallTemplate.taskDelete(circleEntities.getCircleName(), taskEntitye.getTaskName(),"任务已被"+controlUser.getUserName()+"删除"
									, k.getSmallOpenId(), circleEntities.getCircleId(), taskEntitye.getTaskId(), fromId);
							SmallMessageManager.sendTemplateMessage(json);
							userService.updateSmallFromIdState(k.getUserId(), fromId, UserService.SMALL_FROM_ID_STATE_USED);
						}
					}
			});
		}

	}

	@Override
	public void taskRemind(Long taskId,String userFlag) {

		TaskEntity taskEntitye = taskService.selectTaskBase(taskId);

		Long circleId = circleService.selectOnlyCircleIdByTask(taskEntitye.getTaskId()) ;
		String circleName = circleService.selectCircleName(circleId) ;

		List<NotifiEntity> userList = messageMapper.getTaskNotifiAttentionAndAssigner(taskEntitye.getTaskId(),null);

		Map<NotifiEntity, Long> notiUser = addTaskMessage(taskEntitye, userList, circleId, TaskMessageType.TASK_REMIND, 0L, null,null,null,null);

		if(notiUser != null && notiUser.size() >0 ) {
			//NotifiEntity controlUser = messageMapper.getMPOpenId(controlUserId,circleEntities.getCircleId()) ;
			notiUser.forEach((k,v)->{
				NotifiEntity newUser = messageMapper.getMPOpenId(k.getUserId(),circleId) ;
				if(SessionManager.userOnline(String.valueOf(k.getUserId()))) {//在线发送通知
					websocketService.sendToUserNotifi(k.getUserId(),0l,circleId, WebsocketService.NotifiPropertise.TASK_REMIND,selectByPrimaryKey(v),userFlag) ;
				}else if( newUser != null && !StringUtils.isNullOrEmpty(newUser.getMpOpenId()) && taskEntitye.getPlanFinishTime() != null) {//公众号通知
					JSONObject json = wxmpTemplate.remindTask(taskEntitye.getTaskName(),
							taskEntitye.getPlanFinishTime().getTime(), newUser.getMpOpenId() , "点击查看详情",circleId,taskEntitye.getTaskId());
					WXSendMessage.getInstance().postMessage(json);
				}else if(k != null && !StringUtils.isNullOrEmpty(k.getSmallOpenId()) && taskEntitye.getPlanFinishTime() != null ) {//小程序服务通知
					String fromId = userService.getFromId(k.getUserId());
					if (!StringUtils.isNullOrEmpty(fromId)) { //服务号消息的发送
						JSONObject json = wxSmallTemplate.taskRemind(circleName, taskEntitye.getTaskName(),"任务提醒"
								, k.getSmallOpenId(), circleId, taskEntitye.getTaskId(), fromId);
						SmallMessageManager.sendTemplateMessage(json);
						userService.updateSmallFromIdState(k.getUserId(), fromId, UserService.SMALL_FROM_ID_STATE_USED);
					}
				}
			});
		}
	}

	@Override
	public Long createNewTaskMessage(TaskEntity taskEntity, Long circleId, Long controlUserId,String userFlag)
	{
		logger.info("createNewTaskMessage="+taskEntity.toString()+"  "+circleId+"  "+controlUserId);
		logger.info(taskEntity.toString());
		if(taskEntity.getAssignerId() != null && taskEntity.getAssignerId() != 0 && !taskEntity.getAssignerId().equals(controlUserId)) {
			Long mId = addTaskMessage(taskEntity, taskEntity.getAssignerId(), circleId, TaskMessageType.TASK_ASSIGNER,
					controlUserId, null);
			NotifiEntity openId = messageMapper.getMPOpenId(taskEntity.getAssignerId(),circleId) ;
			if(SessionManager.userOnline(String.valueOf(taskEntity.getAssignerId()))) {//在线发送通知
				websocketService.sendToUserNotifi(taskEntity.getAssignerId(),controlUserId,circleId, WebsocketService.NotifiPropertise.ASSIGNERED,selectByPrimaryKey(mId), userFlag);
			}else if( openId != null && !StringUtils.isNullOrEmpty(openId.getMpOpenId())) {//公众号通知
				NotifiEntity newUser = messageMapper.getMPOpenId(openId.getUserId(),circleId) ;
				CircleEntity circleEntities = taskService.getCirclesByTask(taskEntity.getTaskId(),controlUserId);
				NotifiEntity controlUser = messageMapper.getMPOpenId(controlUserId,circleEntities.getCircleId()) ;
				JSONObject json = wxmpTemplate.taskAssignerChangeTemplate("有新的任务指派给你",taskEntity.getTaskName(),"",newUser.getUserName(),
						controlUser.getUserName(), openId.getMpOpenId(), circleEntities.getCircleId(), taskEntity.getTaskId());
				WXSendMessage.getInstance().postMessage(json);
			}else if( openId != null && !StringUtils.isNullOrEmpty(openId.getSmallOpenId())) {//小程序服务通知
				String fromId = userService.getFromId(openId.getUserId());
				if (!StringUtils.isNullOrEmpty(fromId)) { //服务号消息的发送
					CircleEntity circleEntities = taskService.getCirclesByTask(taskEntity.getTaskId(), controlUserId);
					NotifiEntity controlUser = messageMapper.getMPOpenId(controlUserId, circleEntities.getCircleId());
					JSONObject json = wxSmallTemplate.createNewTaskTemplate(circleEntities.getCircleName(), taskEntity.getTaskName(),"有新的任务指派给你"
							, openId.getSmallOpenId(), circleId, taskEntity.getTaskId(), fromId);
					SmallMessageManager.sendTemplateMessage(json);
					userService.updateSmallFromIdState(openId.getUserId(), fromId, UserService.SMALL_FROM_ID_STATE_USED);
				}
			}
		}
		return 0L;
	}

	public void addAtMessage(Long circleId,TaskEntity taskEntity,String s,List<NotifiEntity> userIds,CircleUserEntity controlUser,String userFlag) {

		if(userIds != null && controlUser != null && taskEntity != null)
			for (NotifiEntity user : userIds) {
				if(!user.getUserId().equals(controlUser.getUserId())) {
					Long mId = addTaskMessage(taskEntity, user.getUserId(), circleId, TaskMessageType.COMMENT_AT,
							controlUser.getUserId(), s);
					if(SessionManager.userOnline(String.valueOf(user.getUserId()))) {//在线通知
						websocketService.sendToUserNotifi(user.getUserId(),controlUser.getUserId(),circleId, WebsocketService.NotifiPropertise.AT,selectByPrimaryKey(mId), userFlag);
					}else if(user.getUserId() != controlUser.getUserId() && !StringUtils.isNullOrEmpty(user.getMpOpenId())) {//公众号通知
						JSONObject wxm = wxmpTemplate.commentAtString(s,taskEntity.getTaskName(), (taskEntity.getPlanFinishTime()==null?"未指定":Utils.getFormatDateTime(taskEntity.getPlanFinishTime().getTime())), user.getMpOpenId(), "url", circleId, taskEntity.getTaskId());
						WXSendMessage.getInstance().postMessage(wxm);
					}else if(user.getUserId() != controlUser.getUserId() && !StringUtils.isNullOrEmpty(user.getSmallOpenId())) {//小程序服务通知
						String fromId = userService.getFromId(user.getUserId());
						if(!StringUtils.isNullOrEmpty(fromId)) {
							JSONObject wxm = wxSmallTemplate.commentAtString(taskEntity.getTaskName(), s, Utils.getFormatDateTime(System.currentTimeMillis()),controlUser.getUserName(), user.getSmallOpenId(), "url", circleId, taskEntity.getTaskId(), fromId);
							SmallMessageManager.sendTemplateMessage(wxm);
							userService.updateSmallFromIdState(user.getUserId(), fromId, UserService.SMALL_FROM_ID_STATE_USED);
						}
					}
					websocketService.sendToCircleUserNotifi(user.getUserId(),controlUser.getUserId(),circleId, WebsocketService.NotifiPropertise.AT,mId,userFlag);
				}
			}
	}

	/**
	 * 添加任务消息
	 *
	 * @param taskEntity
	 *            任务
	 * @param userId
	 *            通知人
	 * @param circleId
	 *            圈子
	 * @param controlUserId
	 *            制造消息者
	 */
	private Long addTaskMessage(TaskEntity taskEntity, long userId, Long circleId, TaskMessageType taskMessageType, Long controlUserId,String value) {
		try {
			TaskMessageEntity entity = new TaskMessageEntity();
			BeanUtils.copyProperties(taskEntity, entity);
			entity.setEventId(taskMessageType.value());
			entity.setControlUser(controlUserId);
			entity.setValue(value);
			messageMapper.addMessageAboutTask(entity);
			MessageEntity me = new MessageEntity() ;
			me.setUserId(userId);
			me.setMessageReId(entity.getId());
			me.setMessageType(MessageType.TASK_MESSAGE.value());
			me.setCircleId(circleId);
			messageMapper.relationMessageToUser(me);
			return me.getMessageId() ;
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return 0L ;
	}

	/**
	 * 添加任务消息
	 *
	 * @param taskEntity
	 *            任务
	 * @param userIds
	 *            通知人
	 * @param circleId
	 *            圈子
	 * @param controlUserId
	 *            制造消息者
	 *
	 * @Long srcIndex 修改之前的值的ID
	 * @String srcValue 修改之前的值
	 * @Long targetIndex 修改之后的值的ID
	 * @String targetValue 修改之后的值的
	 */
	private Map<NotifiEntity,Long> addTaskMessage(TaskEntity taskEntity, List<NotifiEntity> userIds, Long circleId, TaskMessageType taskMessageType, Long controlUserId,Long srcIndex,String srcValue,Long targetIndex,String targetValue) {
			Map<NotifiEntity,Long> map = new HashMap<>() ;
		try {
			TaskMessageEntity entity = new TaskMessageEntity();
			BeanUtils.copyProperties(taskEntity, entity);
			entity.setEventId(taskMessageType.value());
			entity.setControlUser(controlUserId);
			entity.setSrcIndex(srcIndex);
			entity.setSrcValue(srcValue);
			entity.setTargetIndex(targetIndex);
			entity.setValue(targetValue);
			messageMapper.addMessageAboutTask(entity);

			//将消息关联到用户列表的用户上
			userIds.forEach(k->{

				if(k.getUserId() !=controlUserId) {
					MessageEntity me = new MessageEntity() ;
					me.setUserId(k.getUserId());
					me.setMessageReId(entity.getId());
					me.setMessageType(MessageType.TASK_MESSAGE.value());
					me.setCircleId(circleId);
					messageMapper.relationMessageToUser(me);
					map.put(k,me.getMessageId()) ;
				}else {
					map.put(k,0L) ;
				}
			});

		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return map ;
	}

	/**
	 发送用户在圈子中的任务完成情况
	 */
	@Override
	public void SendUserTaskState() {
		logger.info("send_user_task_state");
		try {
			List<UserTaskStateEntity> uSl = taskMapper.getUserTaskState();
			for( UserTaskStateEntity l: uSl ) {
				//存在已过期,或即将过期的任务
				if(l.getExpire() !=0 || l.getBeExpire() != 0) {
					if(!StringUtils.isNullOrEmpty(l.getMpOpenId())) {
						JSONObject json = wxmpTemplate.userTaskState(("圈子<"+l.getCircleName()+">"),
								"已过期的任务有"+l.getExpire()+"个,即将过期的任务有"+l.getBeExpire()+"个",l.getCircleCreaterName(),(l.getLastTime()==null?"":Utils.getFormatDateTimeYYMMDD(l.getLastTime().getTime())), l.getMpOpenId(),l.getCircleId()) ;
						WXSendMessage.getInstance().postMessage(json);
					}else if(!StringUtils.isNullOrEmpty(l.getOpenId())){
						String fromId = userService.getFromId(l.getUserId());
						if(!StringUtils.isNullOrEmpty(fromId)) {
						JSONObject json = wxSmallTemplate.userTaskState((l.getCircleName()),
								"已过期的任务有"+l.getExpire()+"个,即将过期的任务有"+l.getBeExpire()+"个",Utils.getFormatDateTimeYYMMDD(System.currentTimeMillis()),l.getOpenId(),l.getCircleId(),fromId) ;
							SmallMessageManager.sendTemplateMessage(json);
						}
					}

				}

			}
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
	}

	@Override
	public List<MessageEntity> getMessageByUser(Long userId,Integer readState) {
		return messageMapper.getMessageByUser(userId,readState);
	}

	/**
	 * 设置消息为已读状态
	 * @param userId 消息ID
	 * @param messageIds 消息ID字符串
	 * @return 0表示失败,其他为成功
	 */
	@Override
	public int setMessageReaded(Long userId,String messageIds,String userFlag){
		int re = messageMapper.setMessageReaded(userId,messageIds) ;
		if(re > 0) {
			websocketService.sendToUserNotifi(userId,userId,0L, WebsocketService.NotifiPropertise.MESSAGE_CHANGE,null,userFlag);
		}
		return re ;
	}
}
